package org.wenhua.yuan.and.views.tab_fragment;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.wenhua.yuan.and.views.tab.TabBtnBottomInfo;

import java.util.List;

public class TabBtnFragmentAdapter {

    private FragmentManager mFragmentManager;
    private List<TabBtnBottomInfo<?>> mTabBtnBottomInfoList;
    private Fragment curFragment; // 记录当前fragment

    public TabBtnFragmentAdapter (FragmentManager manager, List<TabBtnBottomInfo<?>> btnInfoList) {
        mFragmentManager = manager;
        mTabBtnBottomInfoList = btnInfoList;
    }

    public void instantiateItem (@NonNull View container, int position) {
        if (mFragmentManager == null) throw new IllegalStateException("FragmentManager实例，须传入并赋值");
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (curFragment != null) {
            transaction.hide(curFragment);
        }
        String fragmentTag = container.getId() + "=" + position;
        Fragment nextFragment = mFragmentManager.findFragmentByTag(fragmentTag);
        if (nextFragment == null) {
            nextFragment = getNextFragment(position);
            if (nextFragment == null) throw new IllegalStateException("nextFragment ：将要显示的fragment不能为空");
            if (!nextFragment.isAdded()) {
                // containerViewId Optional identifier of the container this fragment is to be placed in
                transaction.add(container.getId(), nextFragment, fragmentTag);
            }
        } else {
            transaction.show(nextFragment);
        }

        curFragment = nextFragment;// 保存状态
        transaction.commitNowAllowingStateLoss();
    }

    /**通过tab实体中存储的fragment.class，反射获取fragment对象*/
    private Fragment getNextFragment(int position) {
        try {
            return mTabBtnBottomInfoList.get(position).getFragment().newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getTotalCount() {
        return mTabBtnBottomInfoList == null? 0:mTabBtnBottomInfoList.size();
    }
}
